<template>
  <div class="mainList">
    <div class="searchMain">
      <div class="searchPos" :class="{'boxShow': searchHide}">
        <a-form ref="formSearchRef" :model="formSearch" v-if="columnsDistShow">
          <div class="form-main" :class="{'searchHide': searchHide}">
            <div class="form-item">
              <div class="searchTop-list tess">
                <a-select v-model="formSearch.keywords_type"
                      style="width:165px;"
                      :trigger-props='{trigger:"hover"}'
                      :bordered="false"
                      :options="keywordTypes"
                      default-value="keywords"
                      @change="(v)=>switchKeywordType(formSearch,v)">
                </a-select>
                <a-input v-model="formSearch[formSearch['keywords_type']??'keywords']" allow-clear placeholder="多个请用','割开"/>
              </div>
              <a-form-item :field="formSearch['keywords_type']" label="关键字" label-col-flex="90px" style="display: none;"></a-form-item>
              <a-form-item field="type" label="类型" label-col-flex="90px" class="searchTop-list">
                  <a-select multiple v-model="formSearch.type" :max-tag-count="1" :options="columnsDist.dictObj.data.flrstLegType" :field-names="{ value: 'key', label: 'title' }"
                  placeholder="请选择类型" allow-clear allow-search :virtual-list-props="{height:200}">
                  <template #header>
                      <div style="padding: 6px 12px;">
                        <a-space>
                          <a-checkbox :value="false" @change="handleSelectAll($event,columnsDist.dictObj.data.flrstLegType,'type','key')">全选/清除</a-checkbox>
                          <a-button size="mini" type="outline" @click="handleInverse(columnsDist.dictObj.data.flrstLegType,'type','key')">反选</a-button>
                        </a-space>
                      </div>
                    </template>>
                    </a-select>
                </a-form-item>  
                <a-form-item field="supplier_service_ids" label="供应商" label-col-flex="90px" class="searchTop-list">
                  <a-select multiple v-model="formSearch.supplier_service_ids" :max-tag-count="1" :options="columnsDist.dicthelpApi_supplier_service.data" :field-names="{ value: 'id', label: 'name' }"
                  placeholder="请选择供应商" allow-clear allow-search :virtual-list-props="{height:200}">
                  <template #header>
                      <div style="padding: 6px 12px;">
                        <a-space>
                          <a-checkbox :value="false" @change="handleSelectAll($event,columnsDist.dicthelpApi_supplier_service.data,'supplier_service_ids','id')">全选/清除</a-checkbox>
                          <a-button size="mini" type="outline" @click="handleInverse(columnsDist.dicthelpApi_supplier_service.data,'supplier_service_ids','id')">反选</a-button>
                        </a-space>
                      </div>
                    </template>>
                    </a-select>
                </a-form-item>
                <a-form-item field="user_id" label-col-flex="90px" label="用户" class="searchTop-list">
                    <a-select multiple v-model="formSearch.user_id" :max-tag-count="1" :options="columnsDist.dicthelpApi_customer.data" :field-names="{ value: 'id', label: 'nick' }"
                      placeholder="请选择用户" allow-clear allow-search :virtual-list-props="{height:200}" />                    
                  </a-form-item>  
                <a-form-item field="clearance_id" label="清关公司" label-col-flex="90px" class="searchTop-list">
                    <a-select v-model="formSearch.clearance_id" :max-tag-count="1" :options="columnsDist.dicthelpApi_supplier_clearance.data" :field-names="{ value: 'id', label: 'name' }"
                    placeholder="请选择清关公司" allow-clear allow-search :virtual-list-props="{height:200}">
                      </a-select>
                  </a-form-item>
                  <a-form-item field="declare_id" label="报关代理" label-col-flex="90px" class="searchTop-list">
                    <a-select v-model="formSearch.declare_id" :max-tag-count="1" :options="columnsDist.dicthelpApi_supplier_declare.data" :field-names="{ value: 'id', label: 'name' }"
                    placeholder="请选择报关代理" allow-clear allow-search :virtual-list-props="{height:200}">
                      </a-select>
                  </a-form-item>
                  <a-form-item field="departure_at" label="出发时间" label-col-flex="90px" class="searchTop-list">
                    <a-range-picker
                      showTime
                      v-model="formSearch.departure_at"
                      :time-picker-props="{
                      defaultValue:['00:00:00','23:59:59']
                      }"
                    />
                  </a-form-item>
                  <a-form-item field="arrived_at" label="到站时间" label-col-flex="90px" class="searchTop-list">
                    <a-range-picker
                      showTime
                      v-model="formSearch.arrived_at"
                      :time-picker-props="{
                      defaultValue:['00:00:00','23:59:59']
                      }"
                    />
                  </a-form-item>
                  <a-form-item field="clear_at" label="清关时间" label-col-flex="90px" class="searchTop-list">
                    <a-range-picker
                      showTime
                      v-model="formSearch.clear_at"
                      :time-picker-props="{
                      defaultValue:['00:00:00','23:59:59']
                      }"
                    />
                  </a-form-item>
                    <a-form-item field="channel_admin_id" label="渠道管理员" label-col-flex="90px" class="searchTop-list">
                    <a-select v-model="formSearch.channel_admin_id" :max-tag-count="1" :options="columnsDist.dicthelpApi_user.data" :field-names="{ value: 'id', label: 'nickname' }"
                      placeholder="请选择渠道管理员" allow-clear allow-search :virtual-list-props="{height:200}">
                        </a-select>
                    </a-form-item>
                    <a-form-item field="finance_id" label="财务" label-col-flex="90px" class="searchTop-list">
                    <a-select v-model="formSearch.finance_id" :max-tag-count="1" :options="columnsDist.dicthelpApi_user.data" :field-names="{ value: 'id', label: 'nickname' }"
                      placeholder="请选择财务" allow-clear allow-search :virtual-list-props="{height:200}">
                        </a-select>
                    </a-form-item>
                    <a-form-item field="container_type" label="集装箱规格" label-col-flex="90px" class="searchTop-list">
                    <a-select v-model="formSearch.container_type" :max-tag-count="1" :options="columnsDist.dictObj.data.containerType" :field-names="{label: 'title', value: 'key'}"
                      placeholder="请选择集装箱规格" allow-clear allow-search :virtual-list-props="{height:200}">
                        </a-select>
                    </a-form-item>
            </div>     
            <div class="form-buttom">
              <div>
                <a-button type="primary" html-type="submit" @click="submitSearch" style="margin-right: 10px;">
                  <template #icon>
                    <icon-search/>
                  </template>
                  搜索
                </a-button>
                <a-button @click="resetSearch">
                  <template #icon>
                    <icon-delete/>
                  </template>
                  重置
                </a-button>
              </div>      
              <a-space class="lg:mt-0 mt-2" style="margin-top: 20px;display: flex;justify-content: flex-end;margin-right: 10px">         
                  <a-tooltip content="显隐搜索"><a-button shape="circle" @click="searchHide=!searchHide"  style="margin-right: 10px"><icon-search/></a-button></a-tooltip>
                  <a-tooltip content="设置"><a-button shape="circle" @click="openSetting"><icon-settings/></a-button></a-tooltip>
                </a-space>                  
            </div>
          </div>
        
          <div class="touHide" style="display: flex;justify-content: center;margin-bottom: 10px;">  
            <a-link v-if="searchHide" @click="searchHide=!searchHide" size="small">
              {{ searchHide ? '收起':'' }}
              <template #icon>
                <icon-up v-if="searchHide" />
              </template>
            </a-link>
          </div>
          </a-form>
      </div>
    </div>
    <div class="ma-content-block justify-between p-4 mainTable">
          <!-- 操作按钮 -->
          <div class="top-button">
            <div>
                <a-button type="primary" @click="addAction()">
              <template #icon>
                <icon-plus/>
              </template>
              新增
            </a-button>
            <a-button type="primary" @click="router.push(`/document/waybill/add`)" v-auth="['document:waybill:addParcel']">配货</a-button>
			<ExeclFile />
			<download url="document/waybill/export" type="waybill" :auth="['document:waybill:export']"/>
            </div>
        <a-space class="lg:mt-0 mt-2">         
          <a-tooltip content="显隐搜索"><a-button shape="circle" @click="searchHide=!searchHide" ><icon-search/></a-button></a-tooltip>
          <a-tooltip content="设置"><a-button shape="circle" @click="openSetting"><icon-settings/></a-button></a-tooltip>
        </a-space>
            
        </div>
        <!-- tab切换 -->
        <a-tabs class="ma-tabs mb-1 tabs" @change="clickTap" v-model:active-key="formSearch.status">         
          <a-tab-pane :key="item.key" :title="item.title" v-for="item in shipmentTabs">
            <template #title>
              <slot :name="'tabTitle-' + item.label">{{ item.title }}{{ item.count ? `(${item.count})` : '' }}</slot>
            </template>
          </a-tab-pane>
      </a-tabs>

      <!-- 状态按钮 -->
      <div style="display: flex;">
        <button-group :button-groups="buttonGroups" :dataList="dataList" :crud-ref="crudRef" :selected="selected"
        :currentStatus="currentStatus"/>
        <totalPage ref="totalPage" :auth="['document:waybill:listTotal']" :api="waybill.listTotal" />
      </div> 
      <div ref="tablePrantRef">
      <a-table ref="tableRef" :sticky-header="true" :scrollbar="true" :stripe="true" :scroll="{ x: '100%', y: '100%' }"  :columns="localColumns(columnsData)" :data="dataList" class="table-list" 
    hide-expand-button-on-empty :loading="loading" row-key="id" v-model:selectedKeys="selected" @selection-change="setSelecteds($event)" stripe :row-selection="rowSelection" column-resizable :pagination="false">
      <!--  列表插槽    -->
      <template #tr="{ record }">
                <tr
            class="ma-crud-table-tr"
            @dblclick="editAction(record)"
        />
      </template>
      <template #public_number="{ record }">
          <a-link color="blue" @click="editAction(record)" style="padding: 0;">{{ record.public_number }}</a-link>
          <div class="overflow-hidden text-xs line-clamp-2">
            <div v-if="record.number">{{ record.number }}</div>
            <a-link status="danger" v-if="record.work_order">
              <template #icon>
                <icon-stop/>
              </template>
              问题件
            </a-link>
            <a-link status="danger" v-if="record.work_order && record.work_order.intercept == 1">
              <template #icon>
                <icon-stop/>
              </template>
              拦截
            </a-link>
          </div>
        </template>
        <template #type="{ record }" v-if="columnsDistShow">{{getDictData('dictObj','flrstLegType',record.type,2,columnsDist) }}</template> 
        <template #shipping_schedule_id="{ record }" v-if="columnsDistShow">{{record.schedule_name}}</template> 
        <!-- <template #shipping_schedule_id="{ record }" v-if="columnsDistShow">{{getDictData('attrApi','dicthelpApi_shipping_schedule',record.shipping_schedule_id,3,columnsDist) }}</template>  -->
        <template #supplier_service_id="{ record }" v-if="columnsDistShow">{{getDictData('attrApi','dicthelpApi_supplier_service',record.supplier_service_id,3,columnsDist) }}</template> 
        <template #clearance_id="{ record }" v-if="columnsDistShow">{{getDictData('attrApi','dicthelpApi_supplier_clearance',record.clearance_id,3,columnsDist,columnsDist) }}</template> 
        <template #departure="{ record }" v-if="columnsDistShow">{{getDictData('attrApi','dicthelpApi_place',record.departure,3,columnsDist) }}</template> 
        <template #destination="{ record }" v-if="columnsDistShow">{{getDictData('attrApi','dicthelpApi_place',record.destination,3,columnsDist) }}</template> 
        <template #single_card_user_id="{ record }" v-if="columnsDistShow">{{getDictData('attrApi','dicthelpApi_user',record.single_card_user_id,4,columnsDist) }}</template> 
        <template #channel_admin_id="{ record }" v-if="columnsDistShow">{{getDictData('attrApi','dicthelpApi_user',record.channel_admin_id,4,columnsDist) }}</template> 
        <template #finance_id="{ record }" v-if="columnsDistShow">{{getDictData('attrApi','dicthelpApi_user',record.finance_id,4,columnsDist) }}</template> 
        <template #depot_id="{ record }" v-if="columnsDistShow">{{getDictData('attrApi','dicthelpApi_depot',record.depot_id,3,columnsDist) }}</template>
        <template #container_type="{ record }" v-if="columnsDistShow">{{getDictData('dictObj','WaybillStatus',record.container_type,2,columnsDist) }}</template> 
        <template #created_by="{ record }" v-if="columnsDistShow">{{getDictData('attrApi','dicthelpApi_user',record.created_by,4,columnsDist) }}</template> 
        <template #updated_by="{ record }" v-if="columnsDistShow">{{getDictData('attrApi','dicthelpApi_user',record.updated_by,4,columnsDist) }}</template>
        <template #profit="{ record }">
          <div>{{record.fee?.shipment_income}}</div>
          <div v-if="record.fee?.shipment_income!=record.fee?.profit_estimation" style="font-size: 12px;">{{record.fee?.profit_estimation}}</div>

        </template> 
        <template #expense="{ record }">
          <template v-if="record.flow"><fee-item :total="record.flow.expense" :list="record.flow.expenselist" :audit="record.info?.expense_audit"/></template>
        </template>
      </a-table>
    </div>  
    <!-- 分页 -->
    <div class="foot-list">
      <a-pagination
          :total="pageInfo.total"
          show-total show-jumper show-page-size     
          v-model:current="formSearch.page"
          @change="pageChange"
          @page-size-change="pageSizeChange"
          :page-size-options="[10, 20, 30, 50, 100]"
          :page-size="formSearch.pageSize"
          style="display: inline-flex"
      />
    </div>
    <add-modal-form ref="addModalMormRef" @addClick="tableList" v-if="columnsDistShow"></add-modal-form>
    <add-modal ref="addModalRef"></add-modal>
    <info ref="infoRef"></info>
    <setting ref="settingRef"></setting>
  </div>
</div>

</template>
<script setup>
import {ref, reactive, provide, computed, watch,onMounted,h} from 'vue'
import waybill from '@/api/document/waybill'
import Info from "@/views/document/waybill/info.vue";
import AddModal from "@cps/actionsNew/addModal.vue";
import AddModalForm from "@/views/document/waybill/components/addModalForm.vue";
import tag from '@/api/logistics/tag'
import router from "@/router/index.js";
import route from "@/api/routes/route";
import ButtonGroup from "@cps/actionsNew/buttonGroup.vue";
import { auth, role } from '@/utils/common'
import workOrder from '@/api/logistics/workOrder'
import Download from "@/views/components/downloadNew.vue";
import {getDictData} from "@/utils/crud/dictNew.js";
import FeeItem from "@/views/document/shipment/FeeItem.vue";
import common from "@/api/common.js";
import dicthelpApi from "@/api/dicthelpApi.js";
import ExeclFile from "@/views/components/ExeclFile.vue";
import Setting from "@/views/components/setting.vue";
import {isUndefined, xor,isFunction} from 'lodash'
import {localColumns,tablePrantRefHeight} from "@/utils/crud/culmns.js";
import TotalPage from "@/views/components/totalPage.vue";
import tool from '@/utils/tool'
const addModalRef = ref()
const addModalMormRef = ref()
const crudRef = ref()
const infoRef = ref()
const selected=ref([])
const columnsDistShow=ref(false)
const shipmentTabs=ref([])//tabs赋值
const countList=ref({})
const tableRef = ref()
const tablePrantRef = ref() //tabel 父级高度
const dataList = ref([])
const loading=ref(false)
const totalPage = ref()
//搜索更多是否显示
const searchHide=ref(false)
provide('getDictData',getDictData)

watch([shipmentTabs,countList],
(newValues) => {
  if(shipmentTabs.value!='' && countList.value!=''){
      shipmentTabs.value.forEach(function(item) {
            item.count = countList.value[item.key] ? countList.value[item.key] : 0
      })   
  }
  }
)
const columnsData = ref([  
{title: '主键', dataIndex: 'id',width:150,align:'center',hide:false,},
{title: '提单号', dataIndex: 'public_number',slotName: 'public_number',width:150,hide:true,},
// {title: '提单号', dataIndex: 'number',width:150,hide:true,},
{title: '用户等级', dataIndex: 'user_level',slotName: 'user_level',width:100,align:'center',hide:false,},
{title: '类型', dataIndex: 'type',slotName: 'type',width:70,align:'center',hide:true,},
{title: '船期/航班', dataIndex: 'shipping_schedule_id',slotName: 'shipping_schedule_id',width:100,align:'center',hide:true,},
{title: '供应商', dataIndex: 'supplier_service_id',slotName: 'supplier_service_id',width:100,align:'center',hide:true,},
{
  title: '承运商', 
  dataIndex: 'carrier',
  width:100,align:'center',hide:true,
  formType: "select",
  dict: {
      name: "waybill_carrier",
      props: {
        label: "title",
        value: "key"
      },
      translation: true
    }
},
{title: '清关公司', dataIndex: 'clearance_id',slotName: 'clearance_id',width:100,align:'center',hide:true,},
{title: '路线', dataIndex: 'luxian',width:220,align:'center',hide:true,
  render: ({record}) => {
      if(columnsDistShow){
        return getDictData('attrApi','dicthelpApi_place',record.departure,3,columnsDist.value) + '-' + getDictData('attrApi','dicthelpApi_place',record.destination,3,columnsDist.value)
      }
    }

},
{title: '用户', dataIndex: 'user_list',width:150,align:'center',hide:true,
  render: ({record}) => {
      if(columnsDistShow && record.user_list!=''){
        let str = []
        let has = []
        for(let i = 0 ; i <  record.user_list?.length??0 ;i++){
          let name = getDictData('attrApi','dicthelpApi_customer',record.user_list[i].user_id,5,columnsDist.value)
          if(has.includes(name) || has.length > 3){
            continue;
          }
          has.push(name)
          if(has.length < 3){
            str.push(h('span', {style:'text-overflow:ellipsis;overflow: hidden;display:inline-block'}, name))
            str.push(h('br'))
          }
          if(has.length == 3){
            str.push(h('span','...'))
          }
        }
        return h('div',str)
      }
    }
},
{title: '箱数', dataIndex: 'statistics.0.parcel_count',width:100,align:'center',hide:true,},
{title: '实重', dataIndex: 'statistics.0.weight',width:100,align:'center',hide:true,},
{title: '材重', dataIndex: 'statistics.0.volume_weight',width:100,align:'center',hide:true,},
{title: '体积', dataIndex: 'statistics.0.volume',width:100,align:'center',hide:true,
  render: ({record}) => {
    if(columnsDistShow){
        if(record.statistics?.length<=0 || record.statistics[0]?.volume <= 0){
          return '';
        }
        return h('div',[
          h('span',record.statistics[0].volume),
          h('br'),
          h('span','1:'+(parseInt(record.statistics[0].weight/record.statistics[0].volume))),
        ])
      }
    }
},
{title: '盈亏', dataIndex: 'profit',slotName: 'profit',width:150,align:'center',hide:true,},

// {title: '盈亏', dataIndex: 'fee.profit',width:150,align:'center',hide:true,},
{title: '应付', dataIndex: 'expense',slotName: 'expense',width:150,align:'center',hide:true,},
{title: '最后路由', dataIndex: 'last_route',width:150,align:'center',hide:true,
    render: ({record}) => {
      if(!record.last_route){
        return '';
      }
      if(columnsDistShow){
        return record.last_route.route_type_id > 0 ? 
          h('div',[
            h('span',record.last_route.time),
            
            h('br'),
            h('span',getDictData('attrApi','dicthelpApi_routeTypeList',record.last_route.route_type_id,3,columnsDist.value)),
          ])
           : 
           h('div',[
            h('span',record.last_route.time),
            h('br'),
            h('span',record.last_route.remark),
            
          ])
            
      }
      
    }
},
{title: '标识', dataIndex: 'tags',slotName: 'tags',width:70,align:'center',hide:true,
    render: ({record}) => {
      if(columnsDistShow && record.tags.length>0 && columnsDist.value.dicthelpApi_tags){
        let attrsObj=getDictData('tags','dicthelpApi_tags',record.tags,3,columnsDist.value)
        attrsObj= attrsObj.children.filter(person => person.type);
        return attrsObj
      }
    }

  },
{title: '报关', dataIndex: 'clearance',width:100,align:'center',hide:true,
  render: ({record}) => {
      let num_1 = 0
      let num_2 = 0
      record.clearance.map(item=>{
        num_1 += item.num1 == 1 ? 1 : 0
        num_2 += item.num2 == 1 ? 1 : 0
      })
      return (record.clearance?.length??0) > 0 ? h('div',[
        h('span',{style:{color:'#f00'}},'报关退税:'+num_1),
        h('br'),
        h('span',{style:{color:'#f00'}},'买单报关:'+num_2),
      ]) : ''
    }
},
{title: '备注', dataIndex: 'remark',width:150,align:'center',hide:false,},
{title: '内部备注', dataIndex: 'internal_remark',width:150,align:'center',hide:false,},
{title: '报关代理', dataIndex: 'declare_id',slotName: 'declare_id',width:150,align:'center',hide:false,},
{title: '出发地', dataIndex: 'departure',slotName: 'departure',width:150,align:'center',hide:false,},
{title: '目的地', dataIndex: 'destination',sldotName: 'destination',width:150,align:'center',hide:false,},
{title: '出发时间', dataIndex: 'departure_at',width:90,align:'center',hide:true,},
{title: '到站时间', dataIndex: 'arrived_at',width:90,align:'center',hide:true,},
{title: '清关时间', dataIndex: 'clear_at',width:90,align:'center',hide:true,},
{title: '创建时间', dataIndex: 'created_at',width:90,align:'center',hide:true,},
{title: '截单时间', dataIndex: 'close_at',width:90,align:'center',hide:false,},
{title: '单证员', dataIndex: 'single_card_user_id',slotName: 'single_card_user_id',width:150,align:'center',hide:false,},
{title: '柜号', dataIndex: 'container_no',width:70,align:'center',hide:true,},
{title: '铅封号', dataIndex: 'seal_no',width:70,align:'center',hide:false,},
{title: '货站', dataIndex: 'depot_id',slotName: 'depot_id',width:100,align:'center',hide:false,},
{title: '渠道管理员', dataIndex: 'channel_admin_id',slotName: 'channel_admin_id',width:100,align:'center',hide:false,},
{title: '财务', dataIndex: 'finance_id',slotName: 'finance_id',width:100,align:'center',hide:false,},
{title: '状态', dataIndex: 'status',slotName: 'status',width:70,align:'center',hide:false,},
{title: '集装箱规格', dataIndex: 'container_type',slotName: 'container_type',width:70,align:'center',hide:false,},
{title: '创建者', dataIndex: 'created_by',slotName: 'created_by',width:100,align:'center',hide:false,},
{title: '更新者', dataIndex: 'updated_by',slotName: 'updated_by',width:100,align:'center',hide:false,},
{title: '更新时间', dataIndex: 'updated_at',width:90,align:'center',hide:false,},
]);
const settingRef = ref()
const openSetting=()=>{
  settingRef.value.open()
}
//新增
const addAction=()=>{
  console.log('jjjjjjjjj',addModalMormRef.value)
  addModalMormRef.value.onShow()
}
//详情
const editAction=(record)=>{
  record.date = new Date().getTime();
  infoRef.value.onShow(record)
}

//总页数
const pageInfo = ref({
  currentPage: 1,
  total: 0,
  totalPage:1
})

//table 选择
const rowSelection = reactive({
  type: 'checkbox',
  showCheckedAll: true,
  checkStrictly: true
});
//列表请求数据
const formSearch=reactive({
  type:[],
  supplier_service_ids:[],
  clearance_id: '',
  declare_id: '',
  user_id:[],
  send_at:[],
  arrive_at:[],
  departure_at:[],
  channel_admin_id:'',
  finance_id: '',
  container_type:'', 
  refresh_tabs: 1,
  keywords_type:'keywords',
  page: 1,
  pageSize: 10,
  status: '1',
  })
  //下拉框全选
const handleSelectAll = (status,list,type,typeStus) => {
  if (isUndefined(formSearch[type])) {
    formSearch[type] = []
  }
  console.log('jjj',typeStus)
  if (status) {
    let value=[]
    list.map(item => {
      value.push(item[typeStus])
    })
    console.log('value',value)
    formSearch[type]=value
  } else {
    formSearch[type] = []
  }
}
//下拉框反选
const handleInverse = (list,type,typeStus) => {
  if (isUndefined(formSearch[type])) {
    formSearch[type] = []
  }
  const ids = []
  list.map(item => ids.push(item[typeStus]))
  formSearch[type] = xor(ids, formSearch[type])
}
  const formSearchRef=ref(null)
    //重置
  const resetSearch=(e)=>{
    formSearchRef.value.resetFields();
    console.log('formSearch',formSearch)
    tableList()
  }
 //搜索 
 const submitSearch=(e)=>{
  formSearch.page=1
  formSearch.refresh_tabs=1
  searchHide.value=false
  tableList()
}

  //切换分页
const pageChange=(e)=>{
  if(e){
   formSearch.page=e
    tableList()
  }
}
  //切换条数
const pageSizeChange=(e)=>{
  if(e){
  tool.local.set('pageSize', e)
   formSearch.pageSize=e
    tableList()
  }
}
//行数选中
const setSelecteds = (key) => {
  selected.value = key
}
//tabs切换
const clickTap=(e)=>{
  formSearch.page=1
  formSearch.status=e
  formSearch.refresh_tabs=0
    tableList()
}
    //列表
    const tableList = () => {
      loading.value=true
      formSearch.pageSize=tool.local.get('pageSize') || 10
      waybill.getList(formSearch).then(res => {     
        dataList.value =  res.data.items
        //页数
        pageInfo.value = res.data.pageInfo
        countList.value=res.data.count   
        formSearch.status=res.data.current_type.toString()
        selected.value=[]
        loading.value=false
        tablePrantRefHeight(tablePrantRef.value)
      })      
    }
  
    onMounted(() => {
      tableList()
    })

const keywordTypes = [
  //  转单号   供应商单号
  {value: 'keywords', label: '单号'},
  // {value: 'public_number', label: '系统提单号'},
  {value: 'shipment_no', label: '运单号'},
  {value: 'outer_carrier_tracking_number', label: '转单号',index:'快递单号'},
  {value: 'ext_number', label: '扩展单号'},
  // {value: 'number', label: '客户单号'},
]
const switchKeywordType = (form,value)=>{
  keywordTypes.map(i=>{
    if(form[i.value] && i.value !== value){
      form[value] = form[i.value]
      form[i.value] = undefined
    }
  })
}


const waybillColumns= async (crudRef) => {
  let attrDict=['flrstLegType','containerType','WaybillStatus','countrys','endDeliveryType','shipment_parcel_type','currencyType','ShipmentAttrs','BitControl','taxwith','deliverywith','exportwith','importwith','ChargeType','AttachmentType','tagType','workOrderStatus']
  let [dictObj,dicthelpApi_shipping_schedule,dicthelpApi_supplier_service,dicthelpApi_place,dicthelpApi_user,dicthelpApi_depot,dicthelpApi_supplier,dicthelpApi_customer,dicthelpApi_supplier_clearance,dicthelpApi_supplier_declare,dicthelpApi_feeTypeList,dicthelpApi_tags,dicthelpApi_routeTypeList]=await Promise.all([
    common.getDicts(attrDict),dicthelpApi.shipping_schedule(),dicthelpApi.supplier_service(), dicthelpApi.place(),dicthelpApi.user(),dicthelpApi.depot(),
        dicthelpApi.supplier(),dicthelpApi.customer(),dicthelpApi.supplier_clearance(),dicthelpApi.supplier_declare(),dicthelpApi.feeTypeList({select: 'id,fee_name',cate:4}),dicthelpApi.tags(),dicthelpApi.routeTypeList()
    ])
  return reactive({
        dictObj,
        dicthelpApi_shipping_schedule,
        dicthelpApi_supplier_service,
        dicthelpApi_place,
        dicthelpApi_user,
        dicthelpApi_depot,
        dicthelpApi_supplier,
        dicthelpApi_customer,
        dicthelpApi_supplier_clearance,
        dicthelpApi_supplier_declare,
        dicthelpApi_feeTypeList,
        dicthelpApi_tags,
        dicthelpApi_routeTypeList
    })
}
const columnsDist = ref([])
const dictList = ref({})
const dicthelpApi_user = ref({})
const feeTypeList = ref({})
const supplierList = ref({})
waybillColumns(crudRef).then(res=>{
  console.log('jjjjjjjjjjjj',res)
  columnsDist.value=res
  dictList.value=res.dictObj.data
  dicthelpApi_user.value=res.dicthelpApi_user.data
  feeTypeList.value=res.dicthelpApi_feeTypeList.data
  supplierList.value=res.dicthelpApi_supplier.data
  columnsDistShow.value=true
  let parcelType=res.dictObj.data.WaybillStatus
  if(parcelType){
    let obj={
      id:'',
      title:'全部',
      key:'',
    }    
    parcelType.push(obj)
    shipmentTabs.value=parcelType
  }
})
const currentStatus = computed(() => {
  let requestParams = formSearch
  if (!requestParams.status) {
    return null;
  }
  return requestParams.status
})
// const changeStatusButtonText = computed(() => {
//   switch (currentStatus.value) {
//     case '1':
//       return '已订舱'
//     case '2':
//       return '已出发'
//     case '3':
//       return '已到站'
//     case '4':
//       return '已清关'
//     case '5':
//       return '已完成'
//   }
// })
// const changeStatusBack = computed(() => {
//   switch (currentStatus.value) {
//     case '3':
//       return '已订舱'
//     case '4':
//       return '已出发'
//     case '5':
//       return '已到站'
//     case '6':
//       return '已清关'
//   }
// })

const buttonGroups = [
  // {title: '标签', action: '', hideStatus: []},
  // {title: '同步签收运单', api: null, hideStatus: [1, 2, 3, 4, 5,8,9, 7,null]},
  {
    title: '订舱',
    api: waybill.changeBooking,
    hideStatus: [2,3,4,5,8,9,6, 7,null],
    auth: ['document:waybill:changeBooking'],
  },
  {
    title: '出发',
    api: waybill.changeSetOut,
    hideStatus: [1,3,4,5,8,9,6, 7,null],
    auth: ['document:waybill:changeSetOut'],
    form: {
      columns: [
        {
          title: '出发时间', dataIndex: 'date', formType: 'date',showTime:true
        },
      ]
    },
    displayDataIndex: auth('document:waybill:number') ? 'number' : 'public_number'
  },
  {
    title: '到站',
    api: waybill.changeArrived,
    hideStatus: [2,1,4,5,8,9,6, 7,null],
    auth: ['document:waybill:changeArrived'],
    form: {
      columns: [
        {
          title: '到站时间', dataIndex: 'date', formType: 'date',showTime:true
        },
      ]
    },
    displayDataIndex: auth('document:waybill:number') ? 'number' : 'public_number'
  },
  {
    title: '清关',
    api: waybill.changeClearance,
    hideStatus: [2,3,1,5,8,9,6, 7,null],
    auth: ['document:waybill:changeClearance'],
    form: {
      columns: [
        {
          title: '到站时间', dataIndex: 'date', formType: 'date',showTime:true
        },
      ]
    },
    displayDataIndex: auth('document:waybill:number') ? 'number' : 'public_number'
  },
  {
    title: '完成',
    api: waybill.changeOver,
    hideStatus: [2,3,4,1,5,6, 7,8,null],
    auth: ['document:waybill:changeOver'],
    displayDataIndex: auth('document:waybill:number') ? 'number' : 'public_number'
  },
  {
    title: '提柜',
    api: waybill.changeTake,
    hideStatus: [2,3,4,1,9,6, 7,8,null],
    auth: ['document:waybill:changeTake'],
    displayDataIndex: auth('document:waybill:number') ? 'number' : 'public_number'
  },
  {
    title: '到仓',
    api: waybill.changeGet,
    hideStatus: [2,3,4,1,5,6, 7,9,null],
    auth: ['document:waybill:changeGet'],
    displayDataIndex: auth('document:waybill:number') ? 'number' : 'public_number'
  },
  {
    title: '作废',
    api: waybill.changeVoid,
    hideStatus: [2,3,4,5,8,9,1, 7,null],
    auth: ['document:waybill:changeVoid'],
    displayDataIndex: auth('document:waybill:number') ? 'number' : 'public_number'
  },
  {
    title: '审计',
    api: waybill.auditPass,
    AuditShow: true,
    form: {
      columns: [
        {
          title: '操作', dataIndex: 'types', formType: 'checkbox', dict: {
            data: [
              {label: '应付-仅流水', value: 3},
              {label: '应付-提单及流水', value: 4},
            ]
          },
          commonRules: {
            required: true,
            message: "请选择操作类型"
          },
        },
      ]
    },
    hideStatus: [1,2,3,7,null],
    auth: ['document:waybill:audit'],
    displayDataIndex: auth('document:waybill:number') ? 'number' : 'public_number'
  },
  {
    title: '反审计',
    api: waybill.auditRefuse,
    AuditShow: true,
    form: {
      columns: [
        {
          title: '操作', dataIndex: 'types', formType: 'checkbox', dict: {
            data: [
              {label: '应付-仅流水', value: 3},
              {label: '应付-运单及流水', value: 4},
            ]
          },
          commonRules: {
            required: true,
            message: "请选择操作类型"
          },
        },
      ]
    },
    hideStatus: [1,2,3,7,null],
    auth: ['document:waybill:audit'],
    displayDataIndex: auth('document:waybill:number') ? 'number' : 'public_number'
  },
  // {title: '问题件', api: null, hideStatus: [6]},
  // {title: '更新统计', api: null, hideStatus: []},
  {
    title: '标识', AuditShow: true, api: tag.set,
    auth:['logistics:tag:set'],
    form: {
      form: {
        about_type: 1
      },
      columns: [
        {
          title: '操作', dataIndex: 'type', formType: 'select', dict: {
            data: [
              {label: '添加', value: 1},
              {label: '移除', value: 2},
              {label: '设置', value: 3},
              {label: '清除全部', value: 4},
            ]
          },
          commonRules: {
            required: true,
            message: "请选择操作类型"
          },
        },
        {
          title: '标识', dataIndex: 'tag_ids', formType: 'checkbox', dict: {
            url: 'logistics/tag/list',
            props: {label: 'name', value: 'id'},
            translation: true,
            params: {select: 'id,name', type: 2},
          },
        },
  
      ]
    },
    displayDataIndex: auth('document:waybill:number') ? 'number' : 'public_number'
  },
  // {
  //   title: '批量修改', api: shipment.updateBatch, hideStatus: [], form: {
  //     options: {
  //       layout: 'vertical'
  //     },
  //     form: {
  //       remark_type: 2,
  //       internal_remark_type: 2,
  //     },
  //     columns: [
  //       {
  //         formType: 'grid-tailwind',
  //         colNumber: 2,
  //         cols: [
  //           {
  //             formList: [
  //               {title: '服务', dataIndex: 'service_id', formType: 'select', dict: dictHelp.service},
  //               // {title: '供应商服务', dataIndex: 'service_id',},
  //               {title: '销售代表', dataIndex: 'seller_id', formType: 'select', dict: dictHelp.user},
  //               {title: '客服代表', dataIndex: 'customer_service_id', formType: 'select', dict: dictHelp.user},
  //               {title: '财务代表', dataIndex: 'finance_id', formType: 'select', dict: dictHelp.user},
  //               {title: '归属分公司', dataIndex: 'organization_id', formType: 'select', dict: dictHelp.dept},
  //               // {title: '是否显示拣货图片', dataIndex: 'service_id',},
  //             ],
  //           },
  //           {
  //             formList: [
  //               {title: '关联单号', dataIndex: 'self_reference',},
  //               {title: '备注', dataIndex: 'remark', formType: 'textarea'},
  //               {
  //                 title: '备注选择',
  //                 dataIndex: 'remark_type',
  //                 formType: 'radio',
  //                 type: 'button',
  //                 dict: {data: [{label: '追加', value: 2}, {label: '覆盖', value: 1}]},
  //               },
  //               {title: '内部备注', dataIndex: 'internal_remark', formType: 'textarea'},
  //               {
  //                 title: '内部备注选择',
  //                 dataIndex: 'internal_remark_type',
  //                 formType: 'radio',
  //                 type: 'button',
  //                 dict: {data: [{label: '追加', value: 2}, {label: '覆盖', value: 1}]},
  //               },
  //             ]
  //           }
  //         ]
  //       }
  //     ]
  //   }
  // },
  {
    title: '批量添加路由',
    hideStatus: [5,8,9, 6, 7,null],
    api: route.save,
    form: {
      form: {
        route_1: "1",
        about_type: "App\\Document\\Model\\Waybill",
      },
      columns: [
        {
          dataIndex: "remark",
          title:"描述",
          formType: "input",
          addDisplay:false,
          rules: {required: true, message: "请输入描述"}
        },
        {
          title:"时间",
          formType: "date",
          showTime: true,
          dataIndex: "time",
          rules: {required: true, message: "请选择时间"}
        }
      ]
    },
    auth: ['routes:route:save'],// todo 拆分提单运单添加路由权限
    displayDataIndex: auth('document:waybill:number') ? 'number' : 'public_number'
  },
  // {title:'导出',action:''},
  {
    title: '恢复', api: waybill.changeInit, 
    status: 'danger',
    hideStatus: [1, 2, 3, 4, 5,8,9, 6,null],
    auth: ['document:waybill:changeInit'],
    displayDataIndex: auth('document:waybill:number') ? 'number' : 'public_number'
  },
  // {title:'查看统计',action:''},
  {
    title: '退回上一状态',
    api: waybill.changeBack,
    status: 'danger',
    hideStatus: [1, 2, 3, 7,null],
    auth: ['document:waybill:changeBack'],
    displayDataIndex: auth('document:waybill:number') ? 'number' : 'public_number'
  },
  {
    title: '作废',
    api: waybill.changeVoid,
    status: 'danger',
    auth: ['document:waybill:changeVoid'],
    hideStatus: [6, 7,null],
    displayDataIndex: auth('document:waybill:number') ? 'number' : 'public_number'
  },
  {
    title: '删除',
    api: waybill.deletes,
    status: 'danger',
    auth: ['document:waybill:delete'],
    hideStatus: [1,2, 3, 4, 5,8,9, 6,null],
    displayDataIndex: auth('document:waybill:number') ? 'number' : 'public_number'
  },
  {
    title: '问题件',
    api: workOrder.save,
    auth: ['logistics:workOrder:save'],
    hideStatus: [],
    form: {
      key:'about_id',
      form:{
        title:'问题件',
        about_type:2
      },
      columns: [
        {
          title: '标题', dataIndex: 'title', formType: 'input',
          rules: {required: true, message: "请填写标题"},
        },
        {
          title: '描述', dataIndex: 'remark', formType: 'textarea',
          rules: {required: true, message: "请填写描述"},
        },
        {
          title: "",
          dataIndex: "intercept",
          formType: "checkbox",
          dict:{
            data:[
              {label:'拦截',value:1},
            ]
          },
        },
      ]
    },
    displayDataIndex: auth('document:waybill:number') ? 'number' : 'public_number'
  },
]
provide('tableList',tableList);

provide('crudRef', crudRef)
provide('dictList', dictList) //全部字典
provide('columnsData', columnsData)
provide('columnsDist', columnsDist)
provide('dataList', dataList)
provide('formSearch', formSearch)
provide('selected', selected)
provide('dicthelpApi_user', dicthelpApi_user) //人員
provide('feeTypeList', feeTypeList) //费用类型
provide('supplierList', supplierList) //供应商
</script>
<script> export default {name: 'document:waybill'} </script>
<style>
.form-inline-card > .arco-card-body {
  padding: 0;
  display: grid;
  grid: 1fr / 1fr 1fr 1fr;
}

.form-inline-card > .arco-card-header {
  display: none;
}

.fee-up {
  border-bottom: dashed #777777 1px;
}

.fee-down {
  color: orange;
}
.customer-input-item .arco-btn-group button:first-child{
  display:none;
}
/* .searchTop{
  display: flex;
  align-content: center;
  flex-direction:row;
  flex-wrap: wrap;
} */
.form-main{
  display: flex;
  height: 40px;
  overflow: hidden;
}
.searchHide{
  height: auto;
}
.boxShow{
  box-shadow: 0 10px 10px 10px #ccc;
}
.form-item{
  display: flex;
  flex-direction:row;
  flex-wrap: wrap;
  flex: 1;
}
.form-buttom{
  margin-left:20px;
  width:200px;
}
.searchTop-list{
  width: 20%;
}
.searchTop-list.tess{
  display: flex;
  margin-bottom: 20px;
}
@media (min-width: 601px) and (max-width: 1300px){
		.searchTop-list{
       width: 50%;
		}
}
@media (min-width: 1301px) and (max-width: 1700px){
		.searchTop-list{
       width: 33.33%;
		}
}
.top-button{
  display: flex;
  justify-content: space-between;
}
.top-button button{
  margin-right: 10px;
}
.table-list{
  margin-top:10px;
}
.arco-tabs-content{
  padding:0;
}
.foot-list{
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}
.searchMain{
  position: relative;
}
.searchPos{
  position: absolute;
  left: 0;
  width: 100%;
  top: 0;
  z-index: 800;
  padding: 1rem 1rem 0;
  background: #ffffff;
}
.mainTable{
  padding-top: 68px;
}
.arco-select-view-inner{
  white-space: nowrap;
}
.arco-select-view-inner .arco-tag{
  white-space: nowrap !important;
}
.tabs .arco-tabs-tab{
  min-width: 70px;
  justify-content: center;
}
</style>